<template>
	<el-dialog title="账户充值" v-model="showRechargeDialog" width="600px" :before-close="handleCloseRechargeDialog">
		<div>
			<el-form>
				<el-form-item style="margin-bottom: 0">
					<span style="font-size: 14px"><span style="color: red;">*</span>充值金额（元）:</span>
					<el-input style="color:red" v-model="rechargeAmount" type="number" :min="1"><template
							#prepend>￥</template></el-input>
				</el-form-item>
				<div style="width: 100%;display: flex;justify-content: left;margin-bottom: 15px;margin-top: 2px;">
					<span style="color:#606266;font-size: 12px">请根据使用情况充值，不支持余额提现</span>
				</div>
				<div style="width: 100%;display: flex;justify-content:space-around">
					<span v-for="amount in amountOptions" :key="amount" class="payment-btn"
						:class="{ 'payment-btn-selected': selectedAmount === amount }"
						@click="selectAmount(amount)">￥{{amount}}</span>
				</div>
				<div style="width: 100%;display: flex;justify-content: left;margin: 15px 0;">
					<span style="font-size: 14px">支付方式:</span>
				</div>
				<el-form-item>
					<el-radio-group v-model="paymentMethod">
						<el-radio value="alipay" size="large" border>
							<div style="display: flex;justify-content: left">
								<img src="@/assets/alipay.png" alt=""
									style="width: 30px;height: 30px;line-height: 30px;">
								<span>支付宝</span>
							</div>
						</el-radio>
						<el-radio value="wechat" size="large" border>
							<div style="display: flex;justify-content: left">
								<img src="@/assets/weixin.png" style="width: 30px;height: 30px;" />
								<span>微信支付</span>
							</div>
						</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
		</div>
		<div style="width: 100%;">
			<el-button style="width:100%;" type="primary" @click="handleRecharge"
				:loading="rechargeLoading">去充值</el-button>
		</div>
	</el-dialog>
	<el-dialog :title="paymentDialogTitle" v-model="showPaymentDialog" width="400px" :close-on-click-modal="false"
		:close-on-press-escape="false" :show-close="false">
		<div style="text-align: center">
			<div v-if="paymentStatus === 'pending'">
				<div v-if="paymentMethod === 'wechat'">
					<div ref="qrCodeRef" style="display: flex; justify-content: center; margin-bottom: 20px;">
					</div>
					<p style="color: #666; margin-bottom: 20px;">请使用微信扫描二维码完成支付</p>
				</div>
				<div v-else-if="paymentMethod === 'alipay'">
					<div ref="qrCodeRef" style="display: flex; justify-content: center; margin-bottom: 20px;">
					</div>
					<p style="color: #666; margin-bottom: 20px;">请使用支付宝扫描二维码完成支付</p>
				</div>
				<el-button type="primary" @click="checkPaymentStatus" :loading="checkingPayment">我已支付</el-button>
				<el-button @click="cancelPayment">取消支付</el-button>
			</div>
			<div v-else-if="paymentStatus === 'success'" style="color: #67C23A">
				<el-icon size="50px">
					<CircleCheck />
				</el-icon>
				<p style="font-size: 18px; margin-top: 10px;">支付成功</p>
				<p style="color: #666; margin-top: 10px;">充值金额: ￥{{ rechargeAmount }}</p>
				<el-button type="primary" style="margin-top: 20px;" @click="closePaymentDialog">确定</el-button>
			</div>
			<div v-else-if="paymentStatus === 'failed'" style="color: #F56C6C">
				<el-icon size="50px">
					<CircleClose />
				</el-icon>
				<p style="font-size: 18px; margin-top: 10px;">支付失败</p>
				<p style="color: #666; margin-top: 10px;">{{ paymentError }}</p>
				<div style="margin-top: 20px;">
					<el-button type="primary" @click="retryPayment">重试</el-button>
					<el-button @click="closePaymentDialog">取消</el-button>
				</div>
			</div>
		</div>
	</el-dialog>
	<div class="sticky_search_box">
		<el-card shadow="hover">
			<el-row justify="space-between" class="mb-4" style="background-color: #fff;">
				<div>
					<div style="color: #606266; font-size: 14px">账户余额</div>
					<div style="font-size: 24px; color: #e15b72; font-weight: bold">￥{{balance}}</div>
				</div>
				<el-button style="height:40px" type="primary" @click="showRechargeDialog = true">
					<span><el-icon>
							<Money />
						</el-icon></span>
					<span style="margin:0px 5px">充值</span>
				</el-button>
			</el-row>
			<el-row :gutter="10" class="mb-4" style="background-color: #fff;">
				<el-col :span="4">
					<el-date-picker type="date" v-model="startDate" placeholder="开始日期" format="YYYY-MM-DD"
						value-format="YYYY-MM-DD" style="width: 100%" />
				</el-col>
				<el-col :span="4">
					<el-date-picker type="date" placeholder="结束日期" v-model="endDate" format="YYYY-MM-DD"
						value-format="YYYY-MM-DD" style="width: 100%" />
				</el-col>
				<el-col :span="3">
					<el-select v-model="selectedTransType" placeholder="交易类型" style="width: 100%">
						<el-option label="全部" value="" />
						<el-option v-for="(value, key) in transTypeMap" :key="key" :label="value" :value="key" />
					</el-select>
				</el-col>
				<el-col :span="3">
					<el-select v-model="selectedStatus" placeholder="状态" style="width: 100%">
						<el-option label="全部" value="" />
						<el-option v-for="(value, key) in statusMap" :key="key" :label="value" :value="key" />
					</el-select>
				</el-col>
				<el-col :span="3">
					<el-select v-model="selectedProject" placeholder="项目" style="width: 100%">
						<el-option label="全部" value="" />
						<el-option v-for="(value, key) in orderTypeMap" :key="key" :label="value" :value="key" />
					</el-select>
				</el-col>
				<el-col :span="6">
					<el-button type="primary" @click="fetchTransactionList">搜索</el-button>
					<el-button>重置</el-button>
				</el-col>
			</el-row>
		</el-card>
	</div>
	<el-main style="padding: 0px;">
		<el-card shadow="hover">
			<el-tabs value="1" class="mb-4">
				<el-tab-pane label="交易明细" value="1" />
				<!--          <el-tab-pane label="云机订单" name="2" />-->
				<!--          <el-tab-pane label="静态IP订单" name="3" />-->
				<!--          <el-tab-pane label="预购订单" name="4" />-->
			</el-tabs>
			<el-table :data="tableData" border style="width: 100%" v-loading="loading" max-height="55vh">
				<el-table-column prop="orderId" label="订单号" min-width="180" />
				<el-table-column prop="status" label="状态" width="100">
					<template #default="{ row }">
						<el-tag :type="statusStyleMap[row.status]?.type" effect="plain">
							{{ statusStyleMap[row.status]?.text || row.status }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="payment" label="支付方式" width="100" />
				<el-table-column prop="type" label="交易类型" width="100" />
				<el-table-column prop="time" label="交易时间" width="180" />
				<el-table-column prop="project" label="项目" width="100" />
				<el-table-column prop="amount" label="交易金额 (¥)" width="120">
					<template #default="{row}">
						{{ row.amount !== undefined ? '￥' + row.amount : 'N/A' }}
					</template>
				</el-table-column>
				<el-table-column prop="serial" label="交易流水号" min-width="180" />
				<el-table-column label="操作" width="120" fixed="right">
					<template #default="{ row }">
						<el-button v-if="row.status === 0" type="primary" size="small" @click="handlePayOrder(row)"
							:loading="row.paying">
							支付
						</el-button>
						<span v-else>-</span>
					</template>
				</el-table-column>
			</el-table>
			<div class="mt-4" style="display: flex; justify-content: space-between; align-items: center">
				<span style="font-size: 14px; color: #909399">共 {{ tableData.length }} 条</span>
				<el-pagination layout="prev, pager, next, jumper" :total="pagination.total"
					:page-size="pagination.pageSize" :current-page="pagination.current"
					@current-change="handlePaginationChange" small />
			</div>
		</el-card>
	</el-main>
</template>

<script>
	import QRCode from 'qrcodejs2';
	import {
		CircleCheck,
		CircleClose,
		Money
	} from '@element-plus/icons-vue';
	import request from '@/utils'


	export default {
		name: "TransactionPage",
		components: {
			CircleCheck,
			CircleClose,
			Money
		},
		data() {
			return {
				tableData: [
					// {
					//   orderId: "VMOS-CLOUD173882177769950406",
					//   status: "成功",
					//   payment: "系统",
					//   type: "充值",
					//   time: "2025-02-06 14:02:58",
					//   project: "余额充值",
					//   amount: "0.50",
					//   serial: "VCP173882177769944754",
					// },
				],
				showRechargeDialog: false,
				showPaymentDialog: false,
				rechargeAmount: 5,
				paymentMethod: 'wechat',
				selectedAmount: null,
				amountOptions: [30, 50, 100, 500],
				rechargeLoading: false,
				paymentStatus: 'pending', // pending, success, failed
				paymentError: '',
				checkingPayment: false,
				paymentDialogTitle: '微信支付',
				currentOrderId: '',
				paymentCheckInterval: null,
				balance: 0,
				//tableData: [],
				pagination: {
					current: 1,
					pageSize: 10,
					total: 0
				},
				loading: false,
				statusMap: {
					0: '待支付',
					1: '成功',
					2: '失败',
					3: '超时'
				},
				statusStyleMap: {
					0: {
						type: 'info',
						text: '待支付'
					},
					1: {
						type: 'success',
						text: '成功'
					},
					2: {
						type: 'danger',
						text: '失败'
					},
					3: {
						type: 'warning',
						text: '超时'
					}
				},
				paymentMap: {
					'wechat': '微信支付',
					'alipay': '支付宝',
					'system': '系统赠送'
				},
				orderTypeMap: {
					1: '余额充值',
					2: '云机购买'
				},
				transTypeMap: {
					1: '充值',
					2: '支出'
				},

				selectedStatus: '',
				selectedProject: '',
				selectedTransType: '',
				startDate: '',
				endDate: ''
			};
		},
		watch: {
			paymentMethod(newVal) {
				this.paymentDialogTitle = newVal === 'wechat' ? '微信支付' : '支付宝支付';
			}
		},
		created() {
			this.checkAuthAndFetchProfile();
			this.fetchTransactionList();
		},
		methods: {
			handleRecharge() {
				if (!this.rechargeAmount || this.rechargeAmount <= 0) {
					this.$message.error('请输入正确的充值金额');
					return;
				}

				if (!this.paymentMethod) {
					this.$message.error('请选择支付方式');
					return;
				}
				this.rechargeLoading = true;
				// 调用下单接口
				const params = {
					amount: parseFloat(this.rechargeAmount),
					payment_source: this.paymentMethod,
					remark: ''
				};

				request.post('/order/create', params)
					.then(response => {
						if (response.data.code === 200) {
							// 根据返回的 result_type 处理不同的支付方式
							if (response.data.data.result_type === 'url') {
								// 跳转到第三方支付页面
								window.location.href = response.data.data.data
							} else {
								this.currentOrderId = response.data.data.order_id || ''; // 假设返回中有orderId
								this.showRechargeDialog = false;
								this.showPaymentDialog = true;
								this.initQRCode(response.data.data.data);
								// 开始轮询检查支付状态
								this.startPaymentStatusCheck();
							}

						} else {
							this.$message.error(response.data.data.msg || '下单失败');
						}
					})
					.catch(error => {
						this.$message.error('下单失败: ' + (error.response?.data?.msg || error.message));
					})
					.finally(() => {
						this.rechargeLoading = false;
					});
			},

			initQRCode(qrCodeData) {
				// 清除已有的二维码
				if (this.qrCode) {
					this.qrCode.clear();
					this.qrCode = null;
				}

				// 创建新的二维码
				this.$nextTick(() => {
					this.qrCode = new QRCode(this.$refs.qrCodeRef, {
						text: qrCodeData,
						width: 200,
						height: 200,
						colorDark: "#000000",
						colorLight: "#ffffff",
						correctLevel: QRCode.CorrectLevel.H
					});
				});
			},

			startPaymentStatusCheck() {
				// 先清除已有的定时器
				this.stopPaymentStatusCheck();
				// 设置新的定时器，每5秒检查一次支付状态
				this.paymentCheckInterval = setInterval(() => {
					this.checkPaymentStatus(false); // 不显示loading
				}, 5000);
			},

			stopPaymentStatusCheck() {
				if (this.paymentCheckInterval) {
					clearInterval(this.paymentCheckInterval);
					this.paymentCheckInterval = null;
				}
			},

			checkPaymentStatus(showLoading = true) {
				if (showLoading) {
					this.checkingPayment = true;
				}

				// 这里替换为你的实际支付状态检查API
				request.get(`/order/status?orderId=${this.currentOrderId}`)
					.then(response => {
						if (response.data.code === 200) {
							const status = response.data.data.status; // 假设返回中有status字段
							if (status === 'success') {
								this.paymentStatus = 'success';
								this.fetchTransactionList();
								this.stopPaymentStatusCheck();
								this.checkAuthAndFetchProfile();
								this.$message.success('支付成功');
							} else if (status === 'failed') {
								this.paymentStatus = 'failed';
								this.paymentError = response.data.msg || '支付失败';
								this.stopPaymentStatusCheck();
								this.fetchTransactionList();
								this.checkAuthAndFetchProfile();
							}
						} else {
							this.paymentStatus = 'failed';
							this.paymentError = response.data.msg || '支付状态检查失败';
							this.stopPaymentStatusCheck();
						}
					})
					.catch(error => {
						this.paymentStatus = 'failed';
						this.paymentError = '支付状态检查失败: ' + (error.response?.data?.msg || error.message);
						this.stopPaymentStatusCheck();
					})
					.finally(() => {
						this.checkingPayment = false;
					});
			},

			cancelPayment() {
				this.stopPaymentStatusCheck();
				this.showPaymentDialog = false;
				this.paymentStatus = 'pending';
				this.$message('支付已取消');
			},

			closePaymentDialog() {
				this.showPaymentDialog = false;
				this.paymentStatus = 'pending';
				this.paymentError = '';
			},

			retryPayment() {
				this.paymentStatus = 'pending';
				this.handleRecharge();
			},

			handleCloseRechargeDialog(done) {
				if (this.rechargeLoading) {
					this.$message.warning('正在下单，请稍候');
					return false;
				}
				done();
			},

			selectAmount(amount) {
				this.selectedAmount = amount;
				this.rechargeAmount = amount;
			},
			//更新钱包余额
			async checkAuthAndFetchProfile() {
				const token = localStorage.getItem('token');
				if (token) {
					try {
						const response = await request.get('/user/profile')

						if (response.data.code === 200) {
							this.balance = response.data.data.balance;
						} else {
							console.error('Failed to fetch profile:', response.msg);
						}
					} catch (error) {
						console.error('Error fetching profile:', error);
					}
				}
			},
			async fetchTransactionList() {
				this.loading = true;
				try {
					const response = await request.get('/order/list', {
						params: {
							page: this.pagination.current,
							size: this.pagination.pageSize,
							status: this.selectedStatus,
							project: this.selectedProject,
							trans_type: this.selectedTransType,
							startDate: this.startDate,
							endDate: this.endDate
						}
					});

					if (response.data.code === 200) {
						this.tableData = response.data.data.map(item => this.formatTransactionItem(item));
						this.pagination.total = response.total;
						this.pagination.current = response.current;
						this.pagination.pageSize = response.pageSize;
					} else {
						this.$message.error(response.msg || '获取交易记录失败');
					}
				} catch (error) {} finally {
					this.loading = false;
				}
			},

			formatTransactionItem(item) {
				return {
					id: item.id,
					orderId: item.trade_no,
					status: item.status,
					payment: this.getPaymentText(item.payment_source),
					type: this.getTransTypeText(item.trans_type),
					time: this.formatDateTime(item.pay_time),
					project: this.getOrderTypeText(item.order_type),
					amount: item.actual_amount == 0 ? item.amount : item.actual_amount,
					serial: item.transaction_id || ''
				};
			},
			// 新增处理订单支付的方法
			async handlePayOrder(row) {
				try {
					// 标记为支付中状态 - 直接赋值即可
					row.paying = true;
					// 调用支付接口
					const response = await request.post('/payment/pay', {
						order_id: row.id
					});

					if (response.data.code === 200) {
						if (response.data.data.result_type === 'url') {
							// 跳转到第三方支付页面
							window.location.href = response.data.data.data
						} else {
							// 支付成功，显示二维码支付弹窗
							this.currentOrderId = row.id;
							this.paymentMethod = row.payment === '微信支付' ? 'wechat' : 'alipay';
							this.rechargeAmount = row.amount;
							this.showPaymentDialog = true;
							this.initQRCode(response.data.data.data);
							// 开始轮询检查支付状态
							this.startPaymentStatusCheck();
						}
					} else {
						this.$message.error(response.msg || '支付失败');
					}
				} catch (error) {
					this.$message.error('支付失败: ' + (error.response?.data?.msg || error.message));
				} finally {
					row.paying = false;
				}
			},

			// getStatusText(status) {
			//   // const statusMap = {
			//   //   0: '待支付',
			//   //   1: '成功',
			//   //   2: '失败',
			//   //   3: '超时'
			//   // };
			//   return statusWithStyleMap[status] || '未知状态';
			// },

			getPaymentText(paymentSource) {
				// const paymentMap = {
				//   'wechat': '微信支付',
				//   'alipay': '支付宝',
				//   'system': '系统赠送'
				// };
				return this.paymentMap[paymentSource] || '其他';
			},

			getTransTypeText(transType) {
				return transType === 1 ? '充值' : '支出';
			},

			getOrderTypeText(orderType) {
				// const orderTypeMap = {
				//   1: '余额充值',
				//   2: '云机购买'
				// };
				return this.orderTypeMap[orderType] || '其他';
			},

			formatDateTime(dateTime) {
				if (!dateTime || dateTime === '0001-01-01T00:00:00Z') return '';
				return new Date(dateTime).toLocaleString();
			},

			handlePaginationChange(current, pageSize) {
				this.pagination.current = current;
				this.pagination.pageSize = pageSize;
				this.fetchTransactionList();
			},

			beforeDestroy() {
				this.stopPaymentStatusCheck();
				if (this.qrCode) {
					this.qrCode.clear();
				}
			}
		}
	};
</script>

<style scoped>
	.mb-4 {
		margin-bottom: 16px;
	}

	.payment-btn {
		height: 40px;
		width: 120px;
		border: 1px solid #ccc;
		line-height: 40px;
		border-radius: 12px;
		color: #4c4c4c;
		cursor: pointer;
	}

	.payment-btn:hover {
		border-color: #409EFF;
	}

	.payment-btn-selected {
		border-color: #409EFF;
		background-color: #ecf5ff;
		color: #409EFF;
	}

	.sticky_search_box {
		margin-bottom: 20px;
	}
</style>